﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Transactions;
using AopAlliance.Intercept;
using Flower.Client;
using Flower.Processing.Interruptions;
using Flower.Workflow;
using System.Threading;

namespace Flower.Processing.Advices
{
    internal class Retrying : IMethodInterceptor
    {
        private const string SUSPEND_SCRIPT = "@Suspend";

        private readonly double _waitTimeSec;
        private readonly int _maxTries;

        public Retrying(double waitTimeSec, int maxTries)
        {
            _waitTimeSec = waitTimeSec;
            _maxTries = maxTries;
        }

        public object Invoke(IMethodInvocation invocation)
        {
            if (invocation.Arguments.Length < 1)
            {
                return invocation.Proceed();
            }

            var executionFlagsHolder = invocation.Target as IExecutionFlagsHolder;

            if 
            (
                executionFlagsHolder != null && 
                executionFlagsHolder.ExecutionFlags.HasFlag(ExecutionFlags.DontRetry)
            )
            {
                return invocation.Proceed();
            }

            var processor = invocation.Arguments[0] as Processor;
            if (processor == null)
            {
                return invocation.Proceed();
            }

            int currentActivityPointer = processor.State.__ActivityPointer;

            try
            {
                object retval = invocation.Proceed();
                processor.State.__RetriesCount = 0;
                return retval;
            }
            catch(Exception ex)
            {
                if (ex is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                if (processor.State.__RetriesCount < _maxTries)
                {
                    var suspentionFor =
                        TimeSpan.FromSeconds(_waitTimeSec * (1 << processor.State.__RetriesCount));
                    DateTime moment =
                        DateTime.Now + suspentionFor;

                    processor.Log.Warning(() => string.Format("Exception occured. Retrying at {0}.", moment), ex);
                    
                    processor.State.__ActivityPointer = currentActivityPointer;
                    ++processor.State.__RetriesCount;

                    System.Transactions.Transaction currentTransaction = System.Transactions.Transaction.Current;
                    var transOpts =
                        new TransactionOptions
                        {
                            IsolationLevel = 
                                (currentTransaction != null) ?
                                    currentTransaction.IsolationLevel :
                                    IsolationLevel.ReadCommitted,
                            Timeout = processor.CurrentSettings.ProcessorTransactionTimeout
                        };
                    string linkId;
                    using (var trn = new TransactionScope(TransactionScopeOption.Required, transOpts))
                    {
                        var result = processor.Client.CreateScript()
                            .SetText(SUSPEND_SCRIPT)
                            .AddParameter("pid", processor.Pid)
                            .AddParameter("until", ScriptHelper.GetJsDate(moment))
                            .Execute();

                        linkId = result.Get<string>("linkId");

                        processor.SaveState(true);

                        trn.Complete();
                    }

                    return new Suspention
                    {
                        Stop = true,
                        Until = moment,
                        LinkId = linkId
                    };
                }
                else
                {
                    processor.Log.Error("Exception occured. No reties left.", ex);
                    processor.State.__RetriesCount = 0;
                    
                    return new UnhandledException
                    {
                        Exception = ex
                    };
                }
            }
        }
    }
}
